package com.dj.common.web.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import com.dj.common.web.exception.CoreRestValidationFailHelper;
import com.dj.common.web.rest.ResponsePack;
import com.dj.common.web.service.ValueObject;

public abstract class CoreBaseRestController implements ApplicationContextAware {

	protected ApplicationContext applicationContext;
	
	@InitBinder
    protected void init(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
	
	@Autowired
	protected CoreRestValidationFailHelper validationFailHelper;

	public final void setApplicationContext(final ApplicationContext applicationContext) {
		this.applicationContext = applicationContext;
	}

	
	protected <T extends ValueObject> ResponseEntity<ResponsePack<List<T>>> createResponse(Page<T> page) {
		List<T> list = new ArrayList<>();
		list.addAll(page.getContent());
		ResponsePack<List<T>> env = new ResponsePack<>(list);
		return new ResponseEntity<>(env, HttpStatus.OK);
	}

	protected <T extends ValueObject> ResponseEntity<ResponsePack<List<T>>> createResponse(List<T> list) {
		ResponsePack<List<T>> env = new ResponsePack<>(list);
		return new ResponseEntity<>(env, HttpStatus.OK);
	}
}
